package com.sdonkey.score.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sdonkey.score.bean.FriendBean;
import com.sdonkey.score.bean.UserAccountBean;
import com.sdonkey.score.bean.UserLoginBean;
import com.sdonkey.score.dao.IUserAccountDao;
import com.sdonkey.score.dto.UserAccountVo;
import com.sdonkey.score.service.IUserAccountService;
import com.sdonkey.score.util.AccountUtil;
import com.sdonkey.score.util.MD5;
import com.sdonkey.score.util.StaticVariable;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类描述：实现账户中心部分的后台业务
 * 创建人：赵超
 * 手机号：18701321850
 * 邮箱：18701321850@163.com
 * 创建时间：2016年11月8日 下午4:57:13
 */
@Service
@Transactional
public class UserAccountServiceImpl implements IUserAccountService {
    private Logger logger = Logger.getLogger(UserAccountServiceImpl.class);
    @Autowired
    IUserAccountDao accountCentralDao;
    @Autowired
    private JedisPool jedisPool;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public UserLoginBean queryUserInformation(Long id) {
        UserLoginBean userLoginBean = accountCentralDao.queryUserInformation(id);
        return userLoginBean;
    }

    @Override
    public int update_BasicInformation(UserLoginBean user) {
        return accountCentralDao.update_BasicInformation(user);
    }

    @Override
    public int update_Details(UserLoginBean user) {
        return accountCentralDao.update_Details(user);
    }

    @Override
    public int update_Ad_category(UserLoginBean user) {
        return accountCentralDao.update_Ad_category(user);
    }

    @Override
    public int update_Ad_Key(UserLoginBean user) {
        return accountCentralDao.update_Ad_Key(user);
    }

    @Override
    public int update_User_Hobby(UserLoginBean user) {
        return accountCentralDao.update_User_Hobby(user);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Map<String, Object> friendListByID(String devid, int page) {
        Map<String, Object> map = new HashMap<String, Object>();
        PageHelper.startPage(page, StaticVariable.friend_page_user_num);
        Page<FriendBean> list = (Page<FriendBean>) accountCentralDao.friendListByID(devid);
        List<FriendBean> list2 = new ArrayList<FriendBean>();
        if (list != null) {

            for (FriendBean friendBean : list) {
                if (friendBean != null) {
                    if (friendBean.getImage_url() == null) {
                        friendBean.setImage_url("");
                    } else {
                        friendBean.setImage_url(StaticVariable.user_head_url + friendBean.getImage_url());
                    }
                    list2.add(friendBean);
                }
            }
        }
        if (list != null) {
            map.put("status", "1");
            map.put("nowpage", list.getPageNum());
            map.put("sumpage", list.getPages());
        } else {
            map.put("status", "0");
            map.put("nowpage", 1);
            map.put("sumpage", 1);
        }
        map.put("friendList", list2);

        return map;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Map<String, Object> findMyfriendByCondition(String devid, int page, String condition) {
        Map<String, Object> map = new HashMap<String, Object>();
        int num = StaticVariable.friend_page_user_num;
        if (condition == null) {
            condition = "";
        }
        PageHelper.startPage(page, num);
        Page<FriendBean> list = (Page<FriendBean>) accountCentralDao.friendListByCondition(devid, condition);
        List<FriendBean> list2 = new ArrayList<FriendBean>();
        if (list != null) {
            // 查询出好友的 id 集合
            List<String> fids = accountCentralDao.getFids(devid);
            for (FriendBean friendBean : list) {
                if (friendBean != null) {
                    for (String fid : fids) {
                        if (fid.equals(friendBean.getDevId() + "")) {
                            friendBean.setAlready(1);     //添加已经是好友的标记
                        }
                    }
                    if (friendBean.getImage_url() == null) {
                        friendBean.setImage_url("");
                    } else {
                        friendBean.setImage_url(StaticVariable.user_head_url + friendBean.getImage_url());
                    }
                    list2.add(friendBean);
                }
            }
        }
        if (list != null) {
            map.put("status", "1");
            map.put("nowpage", list.getPageNum());
            map.put("sumpage", list.getPages());
        } else {
            map.put("status", "0");
            map.put("nowpage", 1);
            map.put("sumpage", 1);
        }
        map.put("friendList", list2);

        return map;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Map<String, Object> selectFriendsByFirstLetter(String devid, int page, String first) {
        Map<String, Object> map = new HashMap<String, Object>();
        int num = StaticVariable.friend_page_user_num;
        if (first == null) {
            first = "A";
        }
        PageHelper.startPage(page, num);
        Page<FriendBean> list = (Page<FriendBean>) accountCentralDao.selectFriendsByFirstLetter(devid, first);
        List<FriendBean> list2 = new ArrayList<FriendBean>();
        if (list != null) {
            for (FriendBean friendBean : list) {
                if (friendBean != null) {
                    if (friendBean.getImage_url() == null) {
                        friendBean.setImage_url("");
                    } else {
                        friendBean.setImage_url(StaticVariable.user_head_url + friendBean.getImage_url());
                    }
                    list2.add(friendBean);
                }
            }
        }
        if (list != null) {
            map.put("status", "1");
            map.put("nowpage", list.getPageNum());
            map.put("sumpage", list.getPages());
        } else {
            map.put("status", "0");
            map.put("nowpage", 1);
            map.put("sumpage", 1);
        }
        map.put("friendList", list2);

        return map;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Map<String, Object> selectFriendByFid(Integer friendId) {
        Map<String, Object> map = new HashMap<String, Object>();
        FriendBean friend = accountCentralDao.selectFriendByFid(friendId);
        FriendBean friend2 = new FriendBean();
        if (friend != null) {
            if (friend.getImage_url() == null)
                friend.setImage_url("");
            else
                friend.setImage_url(StaticVariable.user_head_url + friend.getImage_url());
            BeanUtils.copyProperties(friend, friend2);
            map.put("status", "1");
        } else {
            map.put("status", "0");
        }
        map.put("friend", friend2);

        return map;
    }

    @Transactional
    @Override
    public String deletefriend(String userid, String deleteid) {
        String status;
        int i1 = accountCentralDao.deleteFriend(userid, deleteid);
        int i2 = accountCentralDao.deleteFriend(deleteid, userid);
        if (i1 > 0 && i2 > 0) {
            status = "1";
            logger.info("用户" + userid + " 删除好友" + deleteid);
        } else {
            status = "-1";
            logger.error("用户" + userid + " 删除好友" + deleteid + " 失败");
        }
        return status;
    }

    @Override
    public String addfriend(String userid, String adduserid, String news) {
        boolean flag = false;
        Long f = accountCentralDao.queryUserFriendAandB(userid, adduserid);
        if (f != null && f > 0) {
            flag = true;
        }
        if (!flag) {
            try {
                accountCentralDao.addFriend_info(userid, adduserid, news);
                logger.info("用户" + userid + " 添加好友" + adduserid);
                return "1";
            } catch (Exception e) {
                logger.error("用户" + userid + " 添加好友" + adduserid + " 失败");
                return "-1";
            }
        }
        return "0";
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public List<UserAccountVo> queryBankCardsById(String id) {
        List<UserAccountVo> list = accountCentralDao.queryBankCardsById(id);
        List<UserAccountVo> list2 = new ArrayList<>();
        if (list.size() > 0) {
            for (UserAccountVo userAccountVo : list) {
                if (userAccountVo.getUserAccount().getAccountNum() != null) {
                    userAccountVo.setShowAccountNum(
                            AccountUtil.getAccountNum(0, userAccountVo.getUserAccount().getAccountNum()));
                }
                list2.add(userAccountVo);
            }
        }
        return list2;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public UserAccountVo queryBankCardOne(String divId, String accountId) {
        UserAccountVo userAccountVo = accountCentralDao.queryBankCardOne(divId, accountId);
        if (userAccountVo.getUserAccount().getAccountNum() != null) {
            userAccountVo
                    .setShowAccountNum(AccountUtil.getAccountNum(1, userAccountVo.getUserAccount().getAccountNum()));
        }
        return userAccountVo;
    }

    @Override
    public int update_Tel_Num(String id, String tel_num) {
        return accountCentralDao.update_Tel_Num(id, tel_num);
    }

    @Override
    public int update_Balance(String id, String outBalance) {
        return accountCentralDao.update_Balance(id, outBalance);
    }

    @Override
    public int cancelBandingCard(String id, String accountId) {
        return accountCentralDao.cancelBandingCard(id, accountId);
    }

    @Override
    public int addNewBankCard(UserAccountBean userAccount) {
        return accountCentralDao.addNewBankCard(userAccount);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public String getTel_Num_ById(String devId) {
        return accountCentralDao.getTel_Num_ById(devId);
    }

    @Override
    public int saveNewPhone(String id, String tel_num) {
        return accountCentralDao.saveNewPhone(id, tel_num);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public boolean queryishaveUserByMail(String mail) {
        return accountCentralDao.queryishaveUserByMail(mail);
    }

    @Override
    public String updatePsw(String id, String newPsw) {
        String status;
        //验证登陆密码是否和支付密码相同
        String encode = MD5.encode(newPsw);
        Boolean ifSameToOldPsw = encode.equals(accountCentralDao.validateIfSameToLoginPsw(id,1));
        Boolean ifSameToPayPsw = encode.equals(accountCentralDao.validateIfSameToLoginPsw(id,2));
        if (ifSameToOldPsw){
            //与原密码相同
            return "-1";
        }
        if (ifSameToPayPsw) {
            //与支付密码相同
            return "-2";
        }
        try {
            accountCentralDao.updatePsw(id, MD5.encode(newPsw));
            logger.info("用户" + id + " 修改 登陆密码");
            return "1";
        } catch (Exception e) {
            logger.info("用户" + id + " 修改 登陆密码 失败", e);
            return "0";
        }
    }

   /* @Override
    public String updatePayPsw(String id, String oldPayPsw, String newPayPsw) {
        String status;
        try {
            accountCentralDao.updatePayPsw(id, MD5.encode(newPayPsw));
            status = "1";
            logger.info("用户" + id + " 修改 支付密码");
        } catch (Exception e) {
            status = "-1";
            logger.error("用户" + id + " 修改 支付密码 失败", e);
        }
        return status;
    }*/

    @Override
    public String resetPayPsw(String id, String newPayPsw) {
        String status;
        try {
            //验证支付密码是否和登陆密码相同
            String encode = MD5.encode(newPayPsw);
            Boolean ifSameToOldPsw = encode.equals(accountCentralDao.validateIfSameToLoginPsw(id,2));
            Boolean ifSameToLoginPsw = encode.equals(accountCentralDao.validateIfSameToLoginPsw(id,1));
            if (ifSameToOldPsw){
                //与原密码相同
                return "-1";
            }
            if (ifSameToLoginPsw) {
                //与登录密码相同
                return "-2";
            } else {
                accountCentralDao.updatePayPsw(id, encode);
                logger.info("用户" + id + " 修改 支付密码");
                return "1";
            }
        } catch (Exception e) {
            logger.info("用户" + id + " 修改 支付密码 失败", e);
            return "0";
        }
    }

    @Override
    public String addFriendExecute(String id, String adduserid) {
        String status;
        try {
//            accountCentralDao.update_UserAddFriendInfo(id, adduserid);
            accountCentralDao.addFriend(id, adduserid);
            accountCentralDao.addFriend(adduserid, id);
            status = "1";
        } catch (Exception e) {
            status = "-1";
        }
        return status;
    }

    @Override
    public String saveNewMail(String id, String mail) {
        String status;
        try {
            accountCentralDao.saveNewMail(id, mail);
            status = "1";
        } catch (Exception e) {
            status = "-1";
        }
        return status;
    }

    @Override
    public String addFriendUnExecute(String id, String adduserid) {
        String status;
        try {
            accountCentralDao.update_UserAddFriendUnInfo(id, adduserid);
            status = "1";
        } catch (Exception e) {
            status = "-1";
        }
        return status;
    }

    @Override
    public Integer ensureOldPsw(String userId, String oldPsw) {
        return accountCentralDao.ensureOldPsw(userId, oldPsw);
    }

    @Override
    public Integer ensureOldPayPsw(String userId, String oldPayPsw) {
        return accountCentralDao.ensureOldPayPsw(userId, oldPayPsw);
    }

    @Override
    public boolean getPayPswStatus(String userId) {
        return accountCentralDao.getPayPswStatus(userId);
    }

    @Override
    public Boolean getCardStatus(String accountNum, String userId) {
        return accountCentralDao.getCardStatus(accountNum, userId);
    }

    @Override
    public String getPayPswTimes(String userId, Boolean status) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(2);
            String key = MD5.encode(userId + "payPswTimes");
            if (status != null && status) {//密码输入正确时
                if (jedis.exists(key)) {
                    jedis.del(key);
                }
                return "-2";    // 已清除用户支付密码状态
            } else {//密码输入错误 获取剩余可输入次数
                if (status == null) {
                    if (jedis.exists(key)) {
                        String time = jedis.get(key);
                        if (Integer.valueOf(time) < 0) {
                            logger.error("用户" + userId + " 输错支付密码次数过多，账户已锁定");
                        }
                        return time;   // times小于0，支付密码锁定
                    } else {
                        return "5";
                    }
                }
                if (!jedis.exists(key)) {
                    jedis.set(key, "5");
                    jedis.expire(key, 60 * 60 * 3);    // 设置过期时间为三小时
                } else {
                    jedis.decr(key);    // 存的值减 1
                }
                return jedis.get(key);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "-1";
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

}
